package com.sywb.chuangyebao.contract;

import android.media.MediaPlayer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.czt.mp3recorder.MP3Player;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Answer;
import com.sywb.chuangyebao.bean.Question;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.AskActivity;
import com.sywb.chuangyebao.view.QAndADetailActivity;
import com.sywb.chuangyebao.view.TopicActivity;
import com.sywb.chuangyebao.view.dialog.AnswerReplyDialog;
import com.sywb.chuangyebao.view.dialog.ShareDialog;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.view.BaseActivity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public interface AnswerDetailContract {

    interface AnswerDetail extends AnswerCommentContract.AnswerCommentView {

        int getDialogViewHeight();

        long getAnswerId();

        void setZanChanged(boolean isZan);

        void setLikeCount(int likeCount);

        void setNextAnswer(int nextAnswerId);
    }

    class Presenter extends AnswerCommentContract.Presenter<AnswerDetail> implements View.OnClickListener {

        private RichTextView tvQuestionName;
        private LinearLayout llAnswerMe;
        private LinearLayout llAnswerCheck;
        private ImageView ivCollectionUser;
        private ImageView ivUserType;
        private TextView tvCollectionName;
        private TextView tvCollectionTime;
        private TextView tvAddFocus;
        private RichTextView richTextView;
        private ImageView ivImg0;
        private ImageView ivImg1;
        private ImageView ivImg2;
        private LinearLayout llImg;
        private TextView tvAnswerNum;

//        private AudioSeekBar audioSeekBar;

        private ImageView ivMedia;
        private ImageView ivMediaType;
        private SeekBar seekBar;
        private TextView tvAudioTime;
        private TextView tvCurrentTime;
        private LinearLayout llMedia;

        @Override
        public void onStart() {
            super.onStart();

            View headView = mActivity.getLayoutInflater().inflate(R.layout.layout_answer_detail_head, null);
            headView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            headView.findViewById(R.id.ll_answer_me).setOnClickListener(this);
            headView.findViewById(R.id.ll_answer_check).setOnClickListener(this);
            headView.findViewById(R.id.ll_user_head).setOnClickListener(this);

            tvQuestionName = headView.findViewById(R.id.tv_question_name);
            ivCollectionUser = headView.findViewById(R.id.iv_collection_user);
            ivUserType = headView.findViewById(R.id.iv_user_type);
            tvCollectionName = headView.findViewById(R.id.tv_collection_name);
            tvCollectionTime = headView.findViewById(R.id.tv_collection_time);
            tvAddFocus = headView.findViewById(R.id.tv_add_focus);

            richTextView = headView.findViewById(R.id.richTextView);

            ivImg0 = headView.findViewById(R.id.iv_img0);
            ivImg1 = headView.findViewById(R.id.iv_img1);
            ivImg2 = headView.findViewById(R.id.iv_img2);

            ivCollectionUser.setOnClickListener(this);
            ivUserType.setOnClickListener(this);
            tvCollectionName.setOnClickListener(this);

            ivImg0.setOnClickListener(this);
            ivImg1.setOnClickListener(this);
            ivImg2.setOnClickListener(this);

            llImg = headView.findViewById(R.id.ll_img);
            tvAnswerNum = headView.findViewById(R.id.tv_answer_num);

            llMedia = headView.findViewById(R.id.ll_media);
            ivMedia = headView.findViewById(R.id.iv_media);
            tvAudioTime = headView.findViewById(R.id.tv_audio_time);
            ivMediaType = headView.findViewById(R.id.iv_media_type);
            ivMediaType.setOnClickListener(this);
            seekBar = headView.findViewById(R.id.seekbar);
            tvCurrentTime = headView.findViewById(R.id.tv_current_time);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                    answer.progress = seekBar.getProgress();
                    tvCurrentTime.setText(DateTimeUtils.getMediaTimeNumber(answer.progress / 1000));
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

//            audioSeekBar = headView.findViewById(R.id.audio_seekBar);

            tvAddFocus.setOnClickListener(this);
            RichTextView.OnLinkClickListener onLinkClickListener = new RichTextView.OnLinkClickListener() {
                @Override
                public void onAtClick(RichTextView richTextView, Object userId) {
//                    mView.advance(UserIndexActivity.class, userId);
                    Utils.goUserIndex(mView, (Integer) userId);
                }

                @Override
                public void onTopicClick(RichTextView richTextView, Object topicId) {
                    mView.advance(TopicActivity.class, topicId);
                }

                @Override
                public void onEmojiClick(RichTextView richTextView, Object emoji) {

                }

                @Override
                public void onUrlClick(RichTextView richTextView, Object url) {

                }

                @Override
                public void onAllClick(RichTextView richTextView) {

                }
            };
            tvQuestionName.setOnLinkClickListener(onLinkClickListener);
            richTextView.setOnLinkClickListener(onLinkClickListener);
            recyclerAdapter.setHeaderView(headView);
            commonRecycler.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.backgroundGray));

        }

        @Override
        public void isNoData() {
            super.isNoData();
            tvAnswerNum.setVisibility(recyclerAdapter.getDataCount() == 0 ? View.GONE : View.VISIBLE);
            if (mView != null) {
                mView.setCommentCount(recyclerAdapter.getDataCount());
            }
            if (mActivity != null) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        recyclerAdapter.setEmptyView(R.layout.layout_news_no_comment, true);
                    }
                });
            }
        }

        @Override
        public void initData() {
            super.initData();
            initAnswerData(mView.getAnswerId());
        }

        public void initAnswerData(long answerId) {
            HttpUtils.getAnswer(answerId, new HttpCallback<Answer>() {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(final Answer model) {
                    if (model == null) {
                        return;
                    }

                    answer = model;
                    oAnswer = answer;
                    pageNo = 1;
                    initCommentData();

                    //设置提问问题
                    tvQuestionName.setExpandView(false);
                    tvQuestionName.setRichText(model.title, model.questionRichInfoList);

                    //设置回答人头像
                    GlideUtils.getCircleImageToUrl(mActivity, model.avatar, ivCollectionUser, R.drawable.head_image);

                    //设置回答人角色类型
                    Utils.setUserRoleIcon(ivUserType, model.user_role);

                    //设置回答人名称
                    tvCollectionName.setText(model.display_name);

                    //设置回答时间
                    tvCollectionTime.setText(DateTimeUtils.getFormatForMinusMonthDayMinutesSecond(model.create_time));

                    //设置是否关注
                    if (SharedUtils.getString(Constants.USEROPENID).equals(String.valueOf(model.user_id))) {
                        tvAddFocus.setVisibility(View.INVISIBLE);
                    } else {
                        setFollowView();
                    }

                    //设置富文本
                    richTextView.setExpandView(false);
                    richTextView.setRichText(model.content, model.richInfoList);
                    richTextView.setVisibility(TextUtils.isEmpty(model.content) ? View.GONE : View.VISIBLE);

                    //设置图片
                    List<String> imageUrls = model.pic;
                    if (isNotNull(imageUrls)) {
                        llImg.setVisibility(View.VISIBLE);
                        GlideUtils.getNormalIamgeToUrl(mActivity, model.pic.get(0), ivImg0);
                        if (imageUrls.size() > 1) {
                            GlideUtils.getNormalIamgeToUrl(mActivity, model.pic.get(1), ivImg1);
                            if (imageUrls.size() > 2) {
                                GlideUtils.getNormalIamgeToUrl(mActivity, model.pic.get(2), ivImg2);
                            } else {
                                ivImg2.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            ivImg1.setVisibility(View.INVISIBLE);
                            ivImg2.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        llImg.setVisibility(View.GONE);
                    }

                    //设置语音
                    if (!TextUtils.isEmpty(model.audio)) {
                        llMedia.setVisibility(View.VISIBLE);
                        String audioLength;
                        if (model.audioLength.contains(":")) {
                            audioLength = model.audioLength;
                        } else {
                            audioLength = "00:" + (Integer.valueOf(model.audioLength) > 9 ? model.audioLength : "0" + model.audioLength);
                        }
                        tvAudioTime.setText(audioLength);
                        GlideUtils.getNormalIamgeToUrl(mActivity, model.avatar, ivMedia, R.drawable.news_pic_default);
                    } else {
                        llMedia.setVisibility(View.GONE);
                        GlideUtils.getNormalIamgeToUrl(mActivity, model.avatar, ivMedia, R.drawable.image_def);
                    }

                    //设置点赞数
                    mView.setZanChanged(answer.isZan);
                    mView.setLikeCount(model.agree_num);
                    //设置评论数
                    mView.setCommentCount(model.answer_num);
                    //设置下个回答
                    mView.setNextAnswer(model.nextAnswerId);

                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        public void showDialog() {
            if (answer == null) {
                return;
            }
            ShareDialog sharedDialog = ShareDialog.newInstance(Constants.TOPIC_TYPE_ANSWER, answer.answer_id, ShareDialog.TYPE_REPORT, answer.title, answer.content, answer.avatar);
            sharedDialog.show(mView.getMyFragmentManager(), "Shared");
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            if (mp3Player != null) {
                mp3Player.stopPlay();
                mp3Player = null;
            }
        }

        private MP3Player mp3Player;

        private void playAudio(String audioUrl) {
            //播放语音
            if (mp3Player == null) {
                mp3Player = MP3Player.getInstance();
                mp3Player.setOnMP3PlayerListener(new MP3Player.OnMP3PlayerListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        Logger.e("MediaPlayer onCompletion:");
                        seekBar.setProgress(0);
                        tvCurrentTime.setText("00:00");
                        ivMediaType.setImageResource(R.drawable.icon_media_audio);
                        stopTimer();
                    }

                    @Override
                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        Logger.e("MediaPlayer onSeekComplete:");
                    }

                    @Override
                    public void onError(MediaPlayer mediaPlayer) {
                        onCompletion(mediaPlayer);
                        showMessage("播放错误,请稍候再试");
                    }
                });

                mp3Player.setOnMP3PlayerStartListener(new MP3Player.onMP3PlayerStartListener() {
                    @Override
                    public void onStart(MediaPlayer mediaPlayer) {
                        Logger.e("duration:" + mp3Player.getMediaPlayer().getDuration());
                        seekBar.setMax(mp3Player.getMediaPlayer().getDuration());
                        startTimer();
                    }
                });

                mp3Player.startPlay(audioUrl, null);
                isPlaying = true;
                return;
            }
            if (isPlaying) {
                playStop();
            } else {
                mp3Player.startPlay(audioUrl, null);
            }
            isPlaying = !isPlaying;
        }

        public void playStop() {
            if (mp3Player != null) {
                mp3Player.pause();
            }
            if (ivMediaType != null) {
                ivMediaType.setImageResource(R.drawable.icon_media_audio);
            }
            stopTimer();
        }

        private boolean isPlaying;

        private Timer mTimer;
        private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突

        private void startTimer() {
            Logger.e("question.progress:" + answer.progress);
            if (answer.progress > 0) {
                //目前为问题播放
                mp3Player.getMediaPlayer().seekTo(answer.progress);
            }

            //----------定时器记录播放进度---------//
            isChanging = false;
            mTimer = new Timer();
            TimerTask mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (isChanging) {
                        return;
                    }

                    try {
                        if (mp3Player == null || mp3Player.getMediaPlayer() == null) {
                            stopTimer();
                            return;
                        }

                        answer.progress = mp3Player.getMediaPlayer().getCurrentPosition();
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvCurrentTime.setText(DateTimeUtils.getMediaTimeNumber(answer.progress / 1000));
                                seekBar.setProgress(answer.progress);
                            }
                        });
                        Logger.e("currentPosition:" + mp3Player.getMediaPlayer().getCurrentPosition());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            mTimer.schedule(mTimerTask, 0, 500);
        }


        private void stopTimer() {
            if (mp3Player != null) {
                mp3Player.pause();
            }

            if (mTimer != null) {
                isChanging = true;
                mTimer.cancel();
                Logger.e("stopTimer");
            }
        }

        @Override
        public void onClick(View view) {
            if (!((BaseActivity) mActivity).isCanClick(view)) return;
            switch (view.getId()) {
                case R.id.iv_collection_user:
                case R.id.iv_user_type:
                case R.id.tv_collection_name:
                    if (answer == null) {
                        return;
                    }
//                    mView.advance(UserIndexActivity.class, answer.user_id);
                    Utils.goUserIndex(mView, answer.user_id);
                    break;
                case R.id.iv_img0:
                    if (answer == null) {
                        return;
                    }
                    Utils.goBigPic(mActivity, 0, answer.pic);
                    break;
                case R.id.iv_img1:
                    if (answer == null) {
                        return;
                    }
                    Utils.goBigPic(mActivity, 1, answer.pic);
                    break;
                case R.id.iv_img2:
                    if (answer == null) {
                        return;
                    }
                    Utils.goBigPic(mActivity, 2, answer.pic);
                    break;
                case R.id.iv_media_type:
                    if (answer == null) {
                        return;
                    }
                    playAudio(answer.audio);
                    ivMediaType.setImageResource(mp3Player != null && isPlaying ? R.drawable.stop_video_l : R.drawable.icon_media_audio);
                    break;
                case R.id.ll_answer_me:
                    if (answer != null && Utils.checkIsNext(mView.getMyFragmentManager())) {
                        Question question = new Question();
                        question.question_id = answer.question_id;
                        question.title = answer.title;
                        question.richInfoList = answer.questionRichInfoList;
                        mView.advance(AskActivity.class, AskActivity.COMING_TYPE_ANSWER, JSON.toJSONString(question));
                    }
                    break;
                case R.id.ll_answer_check:
                    if (answer == null) {
                        return;
                    }
                    mView.advance(QAndADetailActivity.class, answer.question_id);
                    break;
                case R.id.tv_add_focus:
                    if (answer == null) {
                        return;
                    }
                    //判断是否登录
                    if (!Utils.checkIsLogin()) {
                        return;
                    }
                    HttpUtils.follow(answer.user_id, Constants.TOPIC_TYPE_USER, !answer.isConcern, new HttpCallback<Object>() {

                        @Override
                        public void onStart() {
                            super.onStart();
                            onStartAsync();
                        }

                        @Override
                        public void onSuccess(Object s) {
                            ToastUtils.show(mContext, answer.isConcern ? "取消关注" : "关注成功");
                            answer.isConcern = !answer.isConcern;
                            setFollowView();
                        }

                        @Override
                        public void onError(String strMsg) {
                            super.onError(strMsg);
                            showMessage(strMsg);
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            onFinishAsync();
                        }
                    });
                    break;
            }
        }

        @Override
        protected void initClickedItem(int i) {
            super.initClickedItem(i);
            if (recyclerAdapter.getDataCount() == 0 || i == 0) {
                return;
            }

            answer = recyclerAdapter.getItem(i - 1);
        }

        @Override
        public void onRecyclerItemClick(int i) {
            super.onRecyclerItemClick(i);
            if (recyclerAdapter.getDataCount() == 0 || i == 0) {
                return;
            }
            // mView.advance(AnswerReplyActivity.class, 0, JSON.toJSONString(recyclerAdapter.getItem(i - 1)));

            AnswerReplyDialog dialogFragment = AnswerReplyDialog.newInstance(mView.getDialogViewHeight(), JSON.toJSONString(recyclerAdapter.getItem(i - 1)));
            dialogFragment.show(mView.getMyFragmentManager(), "Reply");

        }

        public void zanAnswer() {
            answer = oAnswer;
            agree(Constants.TOPIC_TYPE_ANSWER);
        }

        private void setFollowView() {
            Utils.setFolllowView(mActivity, answer.isConcern, tvAddFocus);
        }

        @Override
        protected void doOnAgreeSuccess(String topic_Type, Answer clickAnswer) {
            super.doOnAgreeSuccess(topic_Type, answer);
            if (topic_Type.equals(Constants.TOPIC_TYPE_ANSWER)) {
                mView.setZanChanged(clickAnswer.isZan);
                mView.setLikeCount(clickAnswer.agree_num);
            } else {
                recyclerAdapter.notifyDataSetChanged();
            }
        }
    }
}

